/**
 * 
 */
package com.jjt.kiki.crawler;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import org.apache.log4j.Logger;
import com.jjt.kiki.bean.Ip;
import com.jjt.kiki.service.IpService;

/**
 * @author jjtEatJava
 *
 */
public class ProxyOffer {
	private List<Ip> ips =new LinkedList<Ip>();
	private Logger logger = Logger.getLogger(ProxyOffer.class);
	private IpService ipService = new IpService();
	private static class single {
		private static ProxyOffer proxy = new ProxyOffer();
	}

	private ProxyOffer() {
	}

	public static ProxyOffer getInstance() {
		return single.proxy;
	}

	public Ip getIp() {
		synchronized (ProxyOffer.class) {
			if(ips.size()<1) {
				logger.info("ip队列为空，数据库申请扩容");
				while(true) {
					//数据库扩容
					List<Ip> localIps =  ipService.findTop(100);
					if(localIps.size()<=3) {
						logger.info("数据库缓存为0，等待1分钟");
						try {
							Thread.sleep(60*1000);
						} catch (InterruptedException e) {
							// 
							e.printStackTrace();
						}
						continue;
					}
					for(Ip ip : localIps) {
						if(!ips.contains(ip))
							ips.add(ip);
					}
					break;
				}	
			}
			int random = new Random().nextInt(ips.size());
			return ips.get(random);
		}
	}

	public void expired(Ip ip) {
		synchronized (ProxyOffer.class) {
			//队列移除
			ips.remove(ip);
			//数据库移除
			ipService.delete(ip);
		}
	}
}
